package cn.lingyangwl.framework.tool.core.jar;

import cn.lingyangwl.framework.tool.core.exception.BizException;
import cn.lingyangwl.framework.tool.core.file.JarUtils;

import java.net.URL;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * jar构建方式工厂, 判断是引入哪个构建插件
 *
 * @author shenguangyang
 */
public class JarBuildWayFactory {
    /**
     * key 是类名(全名)
     */
    private static final Map<String, CopyResourcesInfo> resourcesInfoMap = new ConcurrentHashMap<>();

    public static JarBuildWay create(CopyResourcesInfo copyResourcesInfo) throws InstantiationException, IllegalAccessException {
        // 判断是否已经被注册过
        String key = copyResourcesInfo.getResourcesInfo().getClass().getName();
        if (resourcesInfoMap.containsKey(key)) {
            throw new BizException("resources [{}] already registered", key);
        }
        resourcesInfoMap.put(key, copyResourcesInfo);

        ResourcesInfo resourcesInfo = copyResourcesInfo.getResourcesInfo();
        URL resourceUrl = resourcesInfo.getClass().getResource("/");
        if (resourceUrl == null) {
            throw new RuntimeException("get resource [" + resourcesInfo.getClass().getName() + "]  fail");
        }

        // jar:file:/D:/project/my/lingyang-framework/commons-test/target/commons-test-1.0.0.jar!/BOOT-INF/classes!/
        String jarFilePath = resourceUrl.getPath();
        if (!JarUtils.isRunningInJar()) {
            return new JarBuildByLocalRun(copyResourcesInfo);
        }
        String loaderPath = System.getProperty("loader.path");
        if (loaderPath != null) {
            return new JarBuildByLoaderExtractLib(loaderPath, copyResourcesInfo);
        }
        if (jarFilePath.contains("!/BOOT-INF")) {
            return new JarBuildBySpringBootMavenPlugin(copyResourcesInfo);
        } else {
            return new JarBuildByMavenAssemblyPlugin(copyResourcesInfo);
        }
    }
}
